package com.example.orderflow.controller.basic;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.example.orderflow.controller.base.ABaseController;
import com.example.orderflow.entity.enums.ResponseCodeEnum;
import com.example.orderflow.entity.po.UserInfo;
import com.example.orderflow.entity.vo.ResponseVO;
import com.example.orderflow.exception.BusinessException;
import com.example.orderflow.service.UserInfoService;
import com.example.orderflow.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import static com.example.orderflow.entity.enums.ResponseCodeEnum.CODE_600;

/****
 * @Description:登录接口
 * @Version: 1.0
 */
@RestController
public class LoginController extends ABaseController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    UserInfoService userInfoService;

    @GetMapping("/testLogin")
    public ResponseCodeEnum testLogin(@RequestParam String userName, @RequestParam String password){
        return CODE_600;
    }

    @PostMapping("/testtologin")
    public ResponseVO testtologin(@RequestParam String userName,
                                  @RequestParam String password){


        String msg = userInfoService.loginService(userName,password);
        if ("ok".equals(msg)) {
            return getSuccessResponseVO("登陆成功");
        }
        throw new BusinessException("账号或密码错误");

    }

    @PostMapping("/login")
    public ResponseVO login(@RequestBody Map<String,String> map){
        String userName = map.get("userName");
        String password = map.get("password");

/*      System.out.println("userName:"+userName);
        System.out.println("password:"+password);*/
        //验证账号密码
        String msg = userInfoService.loginService(userName,password);
        if ("ok".equals(msg)) {

//            Map<String, Object> claims = new HashMap<>();
//            claims.put("userName", JSONUtil.toJsonStr(userName));
//            String token = JwtUtil.createJWT("secretKey", 3600, claims);
//            //存到redis中
//            redisTemplate.opsForValue().set(userName, token);
            UserInfo userInfo = userInfoService.getUserInfoByUserName(userName);
/*            System.out.println(userInfo);*/
            msg = userInfo.getUserName();
            return getSuccessResponseVO(msg);
        }
        throw new BusinessException("账号或密码错误");
    }
}
